{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import lightgbm as lgb\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.model_selection import KFold\n",
    "from sklearn.metrics import r2_score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "code_folding": [
     0
    ]
   },
   "outputs": [],
   "source": [
    "def parseData(df):\n",
    "    \"\"\"\n",
    "    预处理数据\n",
    "    \"\"\"\n",
    "    df['rentType'][df['rentType']=='--'] = '未知方式'\n",
    "    # 转换object类型数据\n",
    "    columns = ['rentType', 'houseFloor', 'houseToward', 'houseDecoration', 'communityName', 'region', 'plate']\n",
    "    for col in columns:\n",
    "        df[col] = df[col].astype('category')\n",
    "        \n",
    "    # 将buildYear列转换为整型数据\n",
    "    tmp = df['buildYear'].copy()\n",
    "    tmp2 = tmp[tmp!='暂无信息'].astype('int')\n",
    "    tmp[tmp=='暂无信息'] = tmp2.mode().iloc[0]\n",
    "    df['buildYear'] = tmp\n",
    "    df['buildYear'] = df['buildYear'].astype('int')\n",
    "    \n",
    "    # 处理pv和uv的空值\n",
    "    df['pv'].fillna(df['pv'].mean(),inplace=True)\n",
    "    df['uv'].fillna(df['uv'].mean(),inplace=True)\n",
    "    df['pv'] = df['pv'].astype('int')\n",
    "    df['uv'] = df['uv'].astype('int')\n",
    "    \n",
    "    # 去掉部分特征\n",
    "    df.drop('communityName',axis=1, inplace=True)\n",
    "    df.drop('city',axis=1,inplace=True)\n",
    "    \n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "code_folding": [
     0
    ]
   },
   "outputs": [],
   "source": [
    "def washData(df_train, df_test):\n",
    "    \"\"\"\n",
    "    清洗数据\n",
    "    \"\"\"\n",
    "    df_train = df_train[df_train['area']<=700]\n",
    "    df_train = df_train[df_train['tradeMoney']<=100000]\n",
    "    \n",
    "    df_train.drop('ID', axis=1, inplace=True)\n",
    "    df_test.drop('ID', axis=1,inplace=True)\n",
    "    \n",
    "    return df_train, df_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "code_folding": [
     0,
     5
    ]
   },
   "outputs": [],
   "source": [
    "def feature(df):\n",
    "    \"\"\"\n",
    "    特征\n",
    "    \"\"\"\n",
    "    # 将houseType转化为‘房间数’，‘厅数’，‘卫生间数’\n",
    "    def parseRoom(info, index):\n",
    "        res = int(info[index*2])\n",
    "        return res\n",
    "    df.insert(3,'室',None)\n",
    "    df.insert(4, '厅', None)\n",
    "    df.insert(5, '卫', None)\n",
    "    df['室'] = df['houseType'].apply(parseRoom, index=0)\n",
    "    df['厅'] = df['houseType'].apply(parseRoom, index=1)\n",
    "    df['卫'] = df['houseType'].apply(parseRoom, index=2)\n",
    "    \n",
    "    df['交易月份'] = df['tradeTime'].apply(lambda x: int(x.split('/')[1]))\n",
    "#     df['pv/uv'] = df['pv'] / df['uv']\n",
    "#     df['房间总数'] = df['室'] + df['厅'] + df['卫']\n",
    "    \n",
    "    df.drop('houseType', axis=1, inplace=True)\n",
    "    df.drop('tradeTime', axis=1, inplace=True)\n",
    "    \n",
    "    categorical_feats = ['rentType', 'houseFloor', 'houseToward', 'houseDecoration', 'region', 'plate']\n",
    "    return df, categorical_feats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "code_folding": [
     0
    ]
   },
   "outputs": [],
   "source": [
    "def getData(feature):\n",
    "    \"\"\"\n",
    "    获取数据\n",
    "    \"\"\"\n",
    "    train = pd.read_csv('input/train_data.csv')\n",
    "    test = pd.read_csv('input/test_a.csv')\n",
    "    \n",
    "    train = parseData(train)\n",
    "    test = parseData(test)\n",
    "    train, test = washData(train, test)\n",
    "    \n",
    "    train, col = feature(train)\n",
    "    test, col = feature(test)\n",
    "    \n",
    "    target = train.pop('tradeMoney')\n",
    "    features = train.columns\n",
    "    categorical_feats = col\n",
    "    \n",
    "    return train, test, target, features, categorical_feats"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\users\\itryagain\\appdata\\local\\conda\\conda\\envs\\tensorflow-gpu\\lib\\site-packages\\ipykernel_launcher.py:5: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n",
      "  \"\"\"\n"
     ]
    }
   ],
   "source": [
    "train, test, target, features, categorical_feats = getData(feature)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Index(['area', 'rentType', '室', '厅', '卫', 'houseFloor', 'totalFloor',\n",
       "       'houseToward', 'houseDecoration', 'region', 'plate', 'buildYear',\n",
       "       'saleSecHouseNum', 'subwayStationNum', 'busStationNum',\n",
       "       'interSchoolNum', 'schoolNum', 'privateSchoolNum', 'hospitalNum',\n",
       "       'drugStoreNum', 'gymNum', 'bankNum', 'shopNum', 'parkNum', 'mallNum',\n",
       "       'superMarketNum', 'totalTradeMoney', 'totalTradeArea', 'tradeMeanPrice',\n",
       "       'tradeSecNum', 'totalNewTradeMoney', 'totalNewTradeArea',\n",
       "       'tradeNewMeanPrice', 'tradeNewNum', 'remainNewNum', 'supplyNewNum',\n",
       "       'supplyLandNum', 'supplyLandArea', 'tradeLandNum', 'tradeLandArea',\n",
       "       'landTotalPrice', 'landMeanPrice', 'totalWorkers', 'newWorkers',\n",
       "       'residentPopulation', 'pv', 'uv', 'lookNum', '交易月份'],\n",
       "      dtype='object')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['rentType', 'houseFloor', 'houseToward', 'houseDecoration', 'region', 'plate']"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "categorical_feats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "params = {\n",
    "    'num_leaves': 31,\n",
    "    'min_data_in_leaf': 20,\n",
    "    'min_child_samples':20,\n",
    "    'objective': 'regression',\n",
    "    'learning_rate': 0.01,\n",
    "    \"boosting\": \"gbdt\",\n",
    "    \"feature_fraction\": 0.8,\n",
    "    \"bagging_freq\": 1,\n",
    "    \"bagging_fraction\": 0.85,\n",
    "    \"bagging_seed\": 23,\n",
    "    \"metric\": 'rmse',\n",
    "    \"lambda_l1\": 0.2,\n",
    "    \"nthread\": 4,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "folds = KFold(n_splits=5, shuffle=True, random_state=2333)\n",
    "\n",
    "oof_lgb = np.zeros(len(train))\n",
    "predictions_lgb = np.zeros(len(test))\n",
    "feature_importance_df = pd.DataFrame()\n",
    "\n",
    "for fold_, (trn_idx, val_idx) in enumerate(folds.split(train.values, target.values)):\n",
    "    print(\"fold {}\".format(fold_))\n",
    "    trn_data = lgb.Dataset(train.iloc[trn_idx], label=target.iloc[trn_idx], categorical_feature=categorical_feats)\n",
    "    val_data = lgb.Dataset(train.iloc[val_idx], label=target.iloc[val_idx], categorical_feature=categorical_feats)\n",
    "\n",
    "    num_round = 10000\n",
    "    clf = lgb.train(params, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=500, early_stopping_rounds = 200)\n",
    "    \n",
    "    oof_lgb[val_idx] = clf.predict(train.iloc[val_idx], num_iteration=clf.best_iteration)\n",
    "    \n",
    "    fold_importance_df = pd.DataFrame()\n",
    "    fold_importance_df[\"feature\"] = features\n",
    "    fold_importance_df[\"importance\"] = clf.feature_importance()\n",
    "    fold_importance_df[\"fold\"] = fold_ + 1\n",
    "    feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)\n",
    "    \n",
    "    predictions_lgb += clf.predict(test, num_iteration=clf.best_iteration) / folds.n_splits\n",
    "    \n",
    "print(\"CV Score: {:<8.5f}\".format(r2_score(target, oof_lgb)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 特征贡献值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cols = (feature_importance_df[[\"feature\", \"importance\"]]\n",
    "        .groupby(\"feature\")\n",
    "        .mean()\n",
    "        .sort_values(by=\"importance\", ascending=False)[:1000].index)\n",
    "\n",
    "best_features = feature_importance_df.loc[feature_importance_df.feature.isin(cols)]\n",
    "\n",
    "plt.figure(figsize=(14,40))\n",
    "sns.barplot(x=\"importance\",\n",
    "            y=\"feature\",\n",
    "            data=best_features.sort_values(by=\"importance\",\n",
    "                                           ascending=False))\n",
    "plt.title('LightGBM Features (avg over folds)')\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成提交数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame(predictions_lgb).apply(round).to_csv('submit.csv',na_rep='\\n',index=False,encoding='utf8',header=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
